package com.ruoyi.core.controller;

import cn.hutool.core.io.FileTypeUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.enums.FileType;
import com.ruoyi.file.domain.Files;
import com.ruoyi.file.domain.bo.FilesBo;
import com.ruoyi.file.domain.vo.FilesVo;
import com.ruoyi.file.service.impl.FilesServiceImpl;
import com.ruoyi.uitls.MultipartFileToFile;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.*;

@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/upload")
public class UploadController extends BaseController {
    @Value("${file.upload.url}")
    private String uploadFilePath;

    @Value("${file.mapper.url}")
    private String uploadMapperFilePath;

    final FilesServiceImpl filesService;

    @PostMapping(value = "/image", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R<Map<String,String>> uploadImg(@RequestBody MultipartFile file) {
        if(ObjectUtils.isEmpty(file) || file.getSize() <=0) {
            return R.fail("上传的文件不能为空");
        }
        File fileTmp = null;
        try {
            fileTmp = MultipartFileToFile.multipartFileToFile(file);
        } catch (Exception e) {
            return R.fail("文件获取失败");
        }
        String type = FileTypeUtil.getType(fileTmp);
        List<String> imageTypes = Arrays.asList("jpg", "jpeg", "png", "gif");
        MultipartFileToFile.deleteTempFile(fileTmp);
        if(!imageTypes.contains(type)){
            return R.fail("图片格式错误，仅支持jpg,jpeg,png,gif");
        }
        File f = new File(uploadFilePath);  // new的一个File对象。
        if (!f.isDirectory()) {
            return R.fail("上传的根路径无效，请联系技术人员");
        }
        // 执行文件存储
        String uuid = IdUtil.fastSimpleUUID();
        String newPath = uploadFilePath + "images" + File.separator ;
        String newMapperPath = uploadMapperFilePath +"images" + File.separator;
        // 原始文件名
        String originalFilename = file.getOriginalFilename();
        //原始文件的后缀：
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //使用uuid重新生成文件。

        /**
         * 目前未使用uuid命名，新的文件如果重名会直接覆盖
         */
        String newName = uuid + suffix;
        File dest = new File(newPath + newName);
        if (!dest.getParentFile().exists()) {
            //避免文件创建失败,如果文件夹不存在，则创建
            dest.getParentFile().mkdirs();
        }
        FilesBo filesBo = new FilesBo();
        filesBo.setFileType(String.valueOf(FileType.IMAGE));
        filesBo.setFileSize(readableFileSize(file.getSize()));
        filesBo.setFlieName(newName);
        filesBo.setMapperPath(newMapperPath+newName);
        filesBo.setRealPath(dest.getPath());
        filesBo.setCreateBy(String.valueOf(getUserId()));

        try {
            file.transferTo(dest);
        } catch (IOException e) {
            return R.fail("文件转存错误");
        }


        Boolean isSave = filesService.insertByBo(filesBo);
        if(!isSave){
            //存储失败删除
            FileUtil.del(dest);
        }

        HashMap<String, String> result = new HashMap<>();
        result.put("path",newMapperPath+newName);
        return R.ok(result);
    }

    @PostMapping(value = "/audio", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R<Map<String,String>> uploadAudio(@RequestBody MultipartFile file) {
        if(ObjectUtils.isEmpty(file) || file.getSize() <=0) {
            return R.fail("上传的文件不能为空");
        }
        File fileTmp = null;
        try {
            fileTmp = MultipartFileToFile.multipartFileToFile(file);
        } catch (Exception e) {
            return R.fail("文件获取失败");
        }
        //校验格式
//        String type = FileTypeUtil.getType(fileTmp);
//        List<String> imageTypes = Arrays.asList("docx", "doc", "png", "gif");
//        MultipartFileToFile.deleteTempFile(fileTmp);
//        if(!imageTypes.contains(type)){
//            return R.fail("图片格式错误，仅支持jpg,jpeg,png,gif");
//        }
        File f = new File(uploadFilePath);  // new的一个File对象。
        if (!f.isDirectory()) {
            return R.fail("上传的根路径无效，请联系技术人员");
        }
        // 执行文件存储
        String uuid = IdUtil.fastSimpleUUID();
        String newPath = uploadFilePath + "audio" + File.separator ;
        String newMapperPath = uploadMapperFilePath +"audio" + File.separator;
        // 原始文件名
        String originalFilename = file.getOriginalFilename();
        //原始文件的后缀：
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //使用uuid重新生成文件。

        /**
         * 目前未使用uuid命名，新的文件如果重名会直接覆盖
         */
        String newName = uuid + suffix;
        File dest = new File(newPath + newName);
        if (!dest.getParentFile().exists()) {
            //避免文件创建失败,如果文件夹不存在，则创建
            dest.getParentFile().mkdirs();
        }
        FilesBo filesBo = new FilesBo();
        filesBo.setFileType(String.valueOf(FileType.AUDIO));
        filesBo.setFileSize(readableFileSize(file.getSize()));
        filesBo.setFlieName(newName);
        filesBo.setMapperPath(newMapperPath+newName);
        filesBo.setRealPath(dest.getPath());
        filesBo.setCreateBy(String.valueOf(getUserId()));

        try {
            file.transferTo(dest);
        } catch (IOException e) {
            return R.fail("文件转存错误");
        }


        Boolean isSave = filesService.insertByBo(filesBo);
        if(!isSave){
            //存储失败删除
            FileUtil.del(dest);
        }

        HashMap<String, String> result = new HashMap<>();
        result.put("path",newMapperPath+newName);
        return R.ok(result);
    }

    @PostMapping("/delete")
    public R<Void> delete(@RequestBody FilesBo filesBo){
        FilesVo filesVo = filesService.getByMapperPath(filesBo.getMapperPath());
        if(ObjectUtils.isEmpty(filesVo)){
            return R.fail("未找到删除文件");
        }

        boolean isDel;
        try {
            File file = new File(filesVo.getRealPath());
            if(!file.isFile()){
                return R.fail("传入的非文件路径");
            }
            isDel = FileUtil.del(file);
        } catch (IORuntimeException e) {
            return R.fail("删除失败,未找到文件");
        }
        if(!isDel){
            return R.fail("删除失败");
        }


        filesService.deletById(filesVo.getId());
        return R.ok();
    }

    /**
     * 获取文件大小，转为b kb MB GB
     * @param size
     * @return
     */
    public static String readableFileSize(long size) {
        if (size <= 0) return "0";
        final String[] units = new String[]{"B", "KB", "MB", "GB", "TB"};
        int digitGroups = (int) (Math.log10(size) / Math.log10(1000));
        return new DecimalFormat("#,##0.##").format(size / Math.pow(1000, digitGroups)) + "" + units[digitGroups];
    }
}
